<!-- 商品信息列表 -->
<template>
  <div class="goods-container">
    <van-card
      v-for="(val, index) in goods"
      :key="index"
      :num="val.stuffCount"
      :price="val.stuffPrice"
      :desc="val.stuffDesc"
      :title="val.stuffName"
      :thumb="val.stuffImg"
    >
      <template #tags>
        <van-tag plain type="danger">hot</van-tag>
      </template>
      <template #footer>
        <van-button size="mini" @click="minus(index)">
          <van-icon name="minus" />
        </van-button>
        <van-button size="mini" @click="add(index)">
          <van-icon name="plus" />
        </van-button>
      </template>
    </van-card>

    <div class="submit">
      <van-submit-bar
        :price="total"
        button-text="提交订单"
        safe-area-inset-bottom
        @submit="submit"
      />
    </div>
  </div>
</template>

<script>
import { Toast } from "vant";
import { getCateById, addOrder } from "../../../api/shop";
import { mapState } from "vuex";
export default {
  name: "Goods",
  props: ["cate_id"],
  data() {
    return {
      goods: [],
    };
  },
  methods: {
    async create_getGoodsById() {
      try {
        let { data } = await getCateById(this.cate_id);
        if (data.status === 500) return Toast.fail(data.message);
        this.goods = data.data;
      } catch (error) {
        console.log(error);
      }
    },
    minus(index) {
      if (this.goods[index].stuffCount !== 0) {
        this.goods[index].stuffCount--;
      }
    },
    add(index) {
      this.goods[index].stuffCount++;
    },
    async submit() {
      let order_goods = this.goods.filter((val) => {
        return val.stuffCount != 0;
      });
      if (order_goods.length === 0) return Toast.fail("未下单任何商品");
      let goods = {
        uid: this.userInfo.userId,
        stuffs: order_goods,
      };
      console.log(goods);
      let { data } = await addOrder(goods);
      console.log(data);
      if (data.status === 500) return Toast.fail(data.message);
      this.$router.replace("/order");
    },
  },
  created() {
    this.create_getGoodsById();
  },

  computed: {
    ...mapState(["userInfo"]),
    total() {
      let sum = 0;
      this.goods.forEach((val) => {
        sum += val.stuffPrice * val.stuffCount;
      });
      return sum * 100;
    },
  },
};
</script>


<style lang= "less" scoped>
.goods-container {
  height: calc(100vh - 134px);
  overflow: auto;
}
</style>